<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>设备校准记录</span>
          <el-button link type="primary" @click="goBack">返回设备列表</el-button>
        </div>
      </template>

      <div v-if="equipmentInfo" class="equipment-info">
        <el-descriptions title="设备信息" :column="3" border>
          <el-descriptions-item label="设备名称">{{ equipmentInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ equipmentInfo.model }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">
            <dict-tag :options="typeOptions" :value="equipmentInfo.type" />
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <dict-tag :options="statusOptions" :value="equipmentInfo.status" />
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ parseTime(equipmentInfo.createTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['qep:calibration:add']"
          >新增校准记录</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['qep:calibration:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['qep:calibration:remove']"
          >删除</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="calibrationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="校准ID" align="center" prop="id" />
        <el-table-column label="校准日期" align="center" prop="calibrationDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.calibrationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="校准结果" align="center" prop="result">
          <template #default="scope">
            <el-tag :type="scope.row.result === '1' ? 'success' : 'danger'">
              {{ scope.row.result === '1' ? '合格' : '不合格' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="校准人员" align="center" prop="calibrator" />
        <el-table-column label="下次校准日期" align="center" prop="nextCalibrationDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.nextCalibrationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['qep:calibration:edit']"
            >修改</el-button>
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['qep:calibration:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改校准记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="calibrationForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备" prop="equipmentId" v-if="!equipmentId">
          <el-select v-model="form.equipmentId" placeholder="请选择设备" filterable>
            <el-option
              v-for="item in equipmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="校准日期" prop="calibrationDate">
          <el-date-picker
            v-model="form.calibrationDate"
            type="date"
            placeholder="选择校准日期"
            style="width: 100%;"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="校准结果" prop="result">
          <el-radio-group v-model="form.result">
            <el-radio label="1">合格</el-radio>
            <el-radio label="0">不合格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="校准人员" prop="calibrator">
          <el-input v-model="form.calibrator" placeholder="请输入校准人员" />
        </el-form-item>
        <el-form-item label="下次校准日期" prop="nextCalibrationDate">
          <el-date-picker
            v-model="form.nextCalibrationDate"
            type="date"
            placeholder="选择下次校准日期"
            style="width: 100%;"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="证书上传" prop="certificate">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            multiple
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <el-button class="ml-3" type="success" @click="submitUpload">
              上传到服务器
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传校准证书或相关文档，支持jpg/png/pdf文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listCalibration, getCalibration, delCalibration, addCalibration, updateCalibration } from '@/api/qep/equipment';
import { listEquipment, getEquipment } from '@/api/qep/equipment';
import { getDicts } from '@/api/system/dict/data';
import { ref, reactive, onMounted, getCurrentInstance, computed } from 'vue';
import { parseTime } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 获取设备ID（如果从设备详情页进入）
const equipmentId = computed(() => route.query.equipmentId);

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);
// 校准记录表格数据
const calibrationList = ref([]);
// 设备选项
const equipmentOptions = ref([]);
// 设备信息
const equipmentInfo = ref(null);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 上传文件列表
const fileList = ref([]);
// 设备类型选项
const typeOptions = ref([]);
// 设备状态选项
const statusOptions = ref([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  equipmentId: undefined,
  calibrationDate: undefined,
  nextCalibrationDate: undefined,
});

// 表单参数
const form = reactive({
  id: undefined,
  equipmentId: undefined,
  calibrationDate: undefined,
  result: "1",
  calibrator: undefined,
  nextCalibrationDate: undefined,
  remark: undefined
});

// 表单校验
const rules = reactive({
  equipmentId: [
    { required: true, message: "设备不能为空", trigger: "change" }
  ],
  calibrationDate: [
    { required: true, message: "校准日期不能为空", trigger: "blur" }
  ],
  result: [
    { required: true, message: "校准结果不能为空", trigger: "change" }
  ],
  calibrator: [
    { required: true, message: "校准人员不能为空", trigger: "blur" }
  ],
  nextCalibrationDate: [
    { required: true, message: "下次校准日期不能为空", trigger: "blur" }
  ],
});

onMounted(() => {
  // 获取字典数据
  getDicts("qep_equipment_type").then(response => {
    typeOptions.value = response.data;
  });
  getDicts("sys_normal_disable").then(response => {
    statusOptions.value = response.data;
  });
  
  // 获取设备列表（用于选择设备）
  listEquipment({ pageSize: 100 }).then(response => {
    equipmentOptions.value = response.rows;
  });
  
  // 如果有设备ID参数，则获取设备信息
  if (equipmentId.value) {
    queryParams.equipmentId = equipmentId.value;
    getEquipment(equipmentId.value).then(response => {
      equipmentInfo.value = response.data;
    });
  }
  
  getList();
});

/** 查询校准记录列表 */
function getList() {
  loading.value = true;
  listCalibration(queryParams).then(response => {
    calibrationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.id = undefined;
  form.equipmentId = equipmentId.value;
  form.calibrationDate = undefined;
  form.result = "1";
  form.calibrator = undefined;
  form.nextCalibrationDate = undefined;
  form.remark = undefined;
  fileList.value = [];
  proxy.resetForm("calibrationForm");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加校准记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getCalibration(id).then(response => {
    Object.assign(form, response.data);
    open.value = true;
    title.value = "修改校准记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["calibrationForm"].validate(valid => {
    if (valid) {
      if (form.id) {
        updateCalibration(form).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCalibration(form).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const calibrationIds = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除校准记录编号为"' + calibrationIds + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delCalibration(calibrationIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

/** 返回设备列表 */
function goBack() {
  router.push({ path: '/basic/equipment' });
}

/** 文件变更处理 */
function handleFileChange(file, fileList) {
  fileList.value = fileList;
}

/** 上传文件 */
function submitUpload() {
  ElMessage.success("文件上传功能待实现");
}
</script>

<style scoped>
.equipment-info {
  margin-bottom: 20px;
}
</style> 